package com.example.schoolblog.blog.Service;

import com.example.schoolblog.blog.Dto.PaginationDTO;
import com.example.schoolblog.blog.Dto.QuestionDTO;
import com.example.schoolblog.blog.Dto.QuestionQueryDTO;
import com.example.schoolblog.blog.Exception.CustomizeErrorCode;
import com.example.schoolblog.blog.Exception.CustomizeException;
import com.example.schoolblog.blog.Mapper.QuestionExtMapper;
import com.example.schoolblog.blog.Mapper.QuestionMapper;
import com.example.schoolblog.blog.Mapper.UserMapper;
import com.example.schoolblog.blog.Model.Question;
import com.example.schoolblog.blog.Model.QuestionExample;
import com.example.schoolblog.blog.Model.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionExtMapper questionExtMapper;

    //查找文章列表
    public PaginationDTO list(String search,Integer page, Integer size){
        if(StringUtils.isNotBlank(search)){
            String[] tags = StringUtils.split(search," ");
            search = Arrays.stream(tags).collect(Collectors.joining("|"));
        }

        PaginationDTO paginationDTO = new PaginationDTO();
        //计算文章的总数
        QuestionQueryDTO questionQueryDTO = new QuestionQueryDTO();
        questionQueryDTO.setSearch(search);
        int totalCount = questionExtMapper.countBySearch(questionQueryDTO);
        //对分页类参数进行设置
        paginationDTO.setPagination(totalCount,page,size);
        //计算数据库查询的偏移量值
        Integer offset = paginationDTO.getPage() < 1 ? 0 : size * (paginationDTO.getPage() - 1);
        //取得当前页的文章内容
        QuestionExample questionExample = new QuestionExample();
        questionExample.setOrderByClause("gmt_create desc");
        questionQueryDTO.setSize(size);
        questionQueryDTO.setPage(offset);
        List<Question> questions = questionExtMapper.selectBySearch(questionQueryDTO);
        List<QuestionDTO> questioDTOList = new ArrayList<>();
        //遍历文章，通过作者查找作者的信息
        for(Question question : questions){
            User user = userMapper.selectByPrimaryKey(question.getCreator());
            QuestionDTO questiondto = new QuestionDTO();
            BeanUtils.copyProperties(question,questiondto);
            questiondto.setUser(user);
            questioDTOList.add(questiondto);
        }
        //对当前页的文章进行封装
        paginationDTO.setData(questioDTOList);
        //返回详细的文章列表
        return paginationDTO;
    }

    public PaginationDTO list(Long id, Integer page, Integer size) {
        PaginationDTO paginationDTO = new PaginationDTO();
        //计算文章的总数
        QuestionExample questionExample = new QuestionExample();
        questionExample.createCriteria().andIdEqualTo(id);
        int totalCount = (int)questionMapper.countByExample(questionExample);
        //对分页类参数进行设置
        paginationDTO.setPagination(totalCount,page,size);
        //计算数据库查询的偏移量值
        Integer offset = size * (paginationDTO.getPage() - 1);
        //取得当前页的文章内容
        QuestionExample example = new QuestionExample();
        example.createCriteria().andCreatorEqualTo(id);
        List<Question> questions = questionMapper.selectByExampleWithRowbounds(example,new RowBounds(offset,size));
        List<QuestionDTO> questioDTOList = new ArrayList<>();
        //遍历文章，通过作者查找作者的信息
        for(Question question : questions){
            User user = userMapper.selectByPrimaryKey(question.getCreator());
            QuestionDTO questiondto = new QuestionDTO();
            BeanUtils.copyProperties(question,questiondto);
            questiondto.setUser(user);
            questioDTOList.add(questiondto);
        }
        //对当前页的文章进行封装
        paginationDTO.setData(questioDTOList);
        //返回详细的文章列表
        return paginationDTO;
    }

    //根据问题id查询问题
    public QuestionDTO getById(Long id) {
        Question question = questionMapper.selectByPrimaryKey(id);
        //问题为空,则抛出异常
        if(question == null){
            throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FIND);
        }
        QuestionDTO questionDTO = new QuestionDTO();
        BeanUtils.copyProperties(question,questionDTO);
        //根据问题作者查找用户
        User user = userMapper.selectByPrimaryKey(question.getCreator());
        questionDTO.setUser(user);
        return questionDTO;
    }

    //创建或者更新问题
    public void createOrUpdate(Question question) {
        //打开一个页面编辑，又打开一个页面删除文章，所以要判断
        if(question.getId() == null){
            //创建
            question.setGmtModified(System.currentTimeMillis());
            question.setGmtModified(question.getGmtCreate());
            question.setCommentCount(0);
            question.setViewCount(0);
            question.setLikeCount(0);
            questionMapper.insert(question);

        }else{
            //更新
            question.setGmtModified(System.currentTimeMillis());
            QuestionExample example = new QuestionExample();
            example.createCriteria().andIdEqualTo(question.getId());
            int update = questionMapper.updateByExampleSelective(question,example);
            //更新不成功就抛异常
            if(update != 1){
                throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FIND);
            }
        }
    }

    //增加浏览量
    public void incView(Long id) {
        Question question = new Question();
        question.setId(id);
        //1为递增数量
        question.setViewCount(1);
        questionExtMapper.incView(question);
    }

    public List<QuestionDTO> selectRelated(QuestionDTO queryDTO) {
        if(StringUtils.isBlank(queryDTO.getTag())){
            return new ArrayList<>();
        }
        String[] tags = StringUtils.split(queryDTO.getTag(), ",");
        String regexpTag = Arrays
                .stream(tags)
                .filter(StringUtils::isNotBlank)
                .map(t -> t.replace("+", "").replace("*", "").replace("?", ""))
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.joining("|"));
        Question question = new Question();
        question.setId(queryDTO.getId());
        question.setTag(regexpTag);
        List<Question> questions = questionExtMapper.selectRelated(question);

        List<QuestionDTO> questionDTOS = questions.stream().map(q -> {
            QuestionDTO questionDTO = new QuestionDTO();
            BeanUtils.copyProperties(q,questionDTO);
            return questionDTO;
        }).collect(Collectors.toList());
        return questionDTOS;
    }
}
